<!--
 * @Description: 
 * @Author: Binggan
 * @Date: 2019-08-02 16:42:27
 * @LastEditors: Binggan
 * @LastEditTime: 2020-03-07 20:20:38
 -->
<template>
  <div style="height:100%">
    <div class="dashboard-desc">
      <h2>系统数据统计</h2>
      <div class="times">
        <p class="times-top">
          <span class="vertical-mid time-wrapper">更新于 {{curTime}}</span>
          <Tooltip class="vertical-mid" content="点击手动刷新">
            <Icon :class='[{rotateInfi:freshFlag},"clickable"]' type="md-refresh" color='#2d8cf0' size='18' @click="refresh(true);" />
          </Tooltip>
        </p>
        <p class="time-bot">
          <span>{{delay}} 秒后自动更新</span>
        </p>
      </div>
    </div>
    <Row :gutter='24' class='dashboard-row'>
      <Col span="10">
      <Card>
        <div slot="title">
          <Avatar icon="ios-people" size="small" style="color: rgb(64, 169, 255); background-color: rgb(230, 247, 255);" />
          <strong class="padding-12">系统用户数量
            <span>(单位：名)</span>
          </strong>
        </div>
        <p class="count-number" style="height:100px;line-height:100px">
          <countTo :startVal='startVal' :endVal='endVal.userNumber' :duration='3000'></countTo>
        </p>
      </Card>
      </Col>
      <Col span="14">
      <Card>
        <div slot="title">
          <Avatar icon="ios-albums-outline" size="small" style="color: rgb(146, 84, 222); background-color: rgb(249, 240, 255);" />
          <strong class="padding-12">新闻点击量排行榜(前三)
            <span>(单位：人次)</span>
          </strong>
        </div>
        <ul class="news-hot-list" style="height:100px;line-height:100px">
          <li class="item" v-for="item in newsHotList" :key="item.id">
            <router-link class="title" :to="'/newsDetail/'+item.id">{{item.title}}（{{item.count}}）</router-link>
            <Tag color="volcano">{{item.newsTypeName}}</Tag>
          </li>
        </ul>
      </Card>
      </Col>
    </Row>
    <Row :gutter='24' class='dashboard-row charts-row'>
      <Col span="12">
      <Card style="height:100%">
        <div slot="title">
          <Avatar icon="md-book" size="small" style="color: rgb(115, 209, 61); background-color: rgb(218, 247, 189);" />
          <strong class="padding-12">新闻类型点击量
            <span>(单位：人次)</span>
          </strong>
        </div>
        <!--创建一个echarts的容器-->
        <!-- <Alert show-icon v-show="!chartUnitsTit.length">暂无相关数据</Alert> -->
        <div id="unitContainer" style="width:100%; height:100%"></div>
      </Card>
      </Col>
      <Col span="12">
      <Card class='dashboard-row'>
        <div slot="title">
          <Avatar icon="md-trending-up" size="small" style="color: #ffa114; background-color: #ffe2b8;" />
          <strong class="padding-12">垃圾类型搜索量
            <span>(单位：人次)</span>
          </strong>
        </div>
        <!--创建一个echarts的容器-->
        <div id="garbageContainer" style="width:100%; height:100%"></div>
      </Card>
      </Col>
    </Row>

  </div>

</template>
<script>
import countTo from "vue-count-to";
import echarts from "echarts";

export default {
  components: { countTo },
  data() {
    return {
      curTime: "",
      delay: 0,
      durration: 120,
      timer: null,
      freshFlag: false,
      startVal: 0,
      endVal: { userNumber: 0 },
      ChartSecond: null,
      ChartUnit: null,
      newsHotList: []
    };
  },
  methods: {
    getCurTime() {
      let date = new Date();
      let hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds();

      hour = this.addZero(hour);
      minute = this.addZero(minute);
      second = this.addZero(second);
      return hour + ":" + minute + ":" + second;
    },
    // 为数字添加0前缀
    addZero(num) {
      if (num < 10) {
        num = "0" + num;
      }
      return num;
    },
    setTimer() {
      //定时器
      console.log("^-^" + this.delay);
      if (this.delay <= 1) {
        this.refresh(false);
      } else {
        this.delay--;
        this.timer = setTimeout(() => {
          this.setTimer();
        }, 1000);
      }
    },
    getUsers() {
      this.$axios.get("/user/findAll").then(res => {
        this.endVal.userNumber = res.data.length;
      });
    },
    getNewsHot() {
      this.$axios.get("news/findAllNews").then(res => {
        if (res.errorCode == 0) {
          let oRes = res.data.sort((a, b) => {
            return b.count - a.count;
          });
          this.newsHotList = oRes.slice(0, 3);
        }
      });
    },
    getNewsTypeNum() {
      this.$axios.get("/news/newsStatistics").then(res => {
        if (res.errorCode == 0) {
          let curPipeData = this.getPipeData(res.data);
          this.drawUnitChart(curPipeData);
        }
      });
    },
    getGarbageSearchNum() {
      this.$axios.get("/garbage/garbageSearchStatistics").then(res => {
        if (res.errorCode == 0) {
          let curPipeData = this.getPipeData(res.data);
          this.drawGarbageChart(curPipeData);
        }
      });
    },
    getPipeData(originData) {
      let calcData = { label: [], seriesData: [] };
      for (let item in originData) {
        calcData.label.push(item);
        calcData.seriesData.push({ name: item, value: originData[item] });
      }
      return calcData;
    },
    refresh(handle) {
      //刷新task
      if (this.freshFlag && handle) {
        this.$Message.warning({
          content: "正在更新，请勿重复刷新",
          duration: 2,
          closable: true
        });
      } else if (!this.freshFlag) {
        clearTimeout(this.timer);
        this.timer = null;
        handle && (this.delay = this.durration);
        this.freshFlag = true;
        // 获取数据
        this.$axios
          .all([
            this.getUsers(),
            this.getNewsHot(),
            this.getNewsTypeNum(),
            this.getGarbageSearchNum()
          ])
          .then(() => {
            setTimeout(() => {
              this.freshFlag = false;
              this.delay = this.durration;
              this.setTimer(false);
              this.curTime = this.getCurTime();
            }, 300);
          });

        console.log("开始刷新------>");
      }
    },
    drawPipeChart(seriesData) {
      let opt = {
        backgroundColor: "#fff",
        tooltip: {
          trigger: "item",
          formatter: "{b} : {c} ({d}%)"
        },
        legend: {
          orient: "vertical",
          left: 10,
          data: seriesData.label
        },
        series: [
          {
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: "center"
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: "30",
                  fontWeight: "bold"
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: seriesData.seriesData.sort(function(a, b) {
              return a.value - b.value;
            })
          }
        ]
      };
      console.log(JSON.stringify(opt));
      return opt;
    },
    drawGarbageChart(seriesData) {
      //
      this.ChartSecond = echarts.init(
        document.getElementById("garbageContainer")
      );
      let options = this.drawPipeChart(seriesData);
      this.ChartSecond.setOption(options);
    },
    drawUnitChart(seriesData) {
      //绘制新闻点击量
      this.ChartUnit = echarts.init(document.getElementById("unitContainer"));
      let options = this.drawPipeChart(seriesData);
      this.ChartUnit.setOption(options);
    }
  },
  created() {},
  beforeDestroy() {
    clearTimeout(this.timer);
    this.timer = null;
  },
  mounted() {
    this.delay = this.durration;
    this.curTime = this.getCurTime();
    this.refresh(false);
    let resizeFlag = false;
    window.addEventListener("resize", () => {
      if (!resizeFlag && this.ChartUnit) {
        resizeFlag = true;
        setTimeout(() => {
          resizeFlag = false;
          this.ChartUnit.resize();
          this.ChartSecond.resize();
        }, 200);
      }
    });
  }
};
</script>
<style lang="scss" scoped>
.dashboard-desc {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 10px 15px;
  border-bottom: 1px solid #e8eaec;
  margin-bottom: 10px;
  overflow: hidden;
  h2 {
    flex: 1;
    font-size: 16px;
  }
  .times {
    .time-wrapper {
      display: inline-block;
      position: relative;
      margin-right: 8px;
      &:before {
        display: inline-block;
        vertical-align: middle;
        content: "";
        border-radius: 6px;
        width: 6px;
        height: 6px;
        background-color: #fdbf62;
        margin-right: 6px;
      }
    }
    .time-bot {
      color: #7689a5;
    }
  }
}
.dashboard-row {
  margin-bottom: 15px;
  .padding-12 {
    padding-left: 6px;
    span {
      font-size: 12px;
      color: #afc0d8;
      font-weight: normal;
      padding-left: 10px;
    }
  }
  .count-number {
    font-size: 40px;
    color: #317eeb;
    text-align: center;
  }
}
.charts-row {
  height: calc(100% - 260px);
}
.clickable {
  cursor: pointer;
  color: #317eeb;
  &:hover {
    text-decoration: underline;
  }
}
.news-hot-list .item {
  display: flex;
  line-height: 30px;
  .title {
    flex: 1;
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
<style lang="scss">
.charts-row,
.charts-row .ivu-col,
.charts-row .ivu-col .ivu-card {
  height: 100%;
}
.charts-row .ivu-col .ivu-card .ivu-card-body {
  height: calc(100% - 45px);
}
</style>
